package com.oneday.nuo.base.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.oneday.nuo.base.config.BaseService;

import com.oneday.nuo.base.dao.NuoRoleAuthDAO;
import com.oneday.nuo.base.entity.NuoRoleAuthEntity;
import com.oneday.nuo.base.entity.NuoRoleAuthViewEntity;
import com.oneday.nuo.base.exception.NuoException;
import com.oneday.nuo.base.service.NuoRoleAuthService;
import com.oneday.nuo.base.service.NuoRoleAuthViewService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * (NuoRoleAuth)表服务实现类
 *
 * @author liushuai
 * @since 2021-03-13 23:37:34
 */
@Service("nuoRoleAuthService")
public class NuoRoleAuthServiceImpl extends BaseService<NuoRoleAuthDAO, NuoRoleAuthEntity> implements NuoRoleAuthService {

    @Autowired
    private NuoRoleAuthDAO nuoRoleAuthDao;
    @Autowired
    private NuoRoleAuthViewService nuoRoleAuthViewService;


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveRoleAuth(Map<String, Object> param) {
       String roleId = (String) param.get("roleId");
       List<String> authIds = (List<String>) param.get("authIds");
       List<String> selectListView = (List<String>) param.get("selectListView");
        if(StrUtil.isEmpty(roleId)){
           throw new NuoException("角色id不能为空");
        }
        LambdaQueryWrapper<NuoRoleAuthEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(NuoRoleAuthEntity::getRoleId,roleId);
        nuoRoleAuthDao.delete(wrapper);
        List<NuoRoleAuthEntity> lists = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(authIds)){
            authIds.forEach(res->{
                lists.add(NuoRoleAuthEntity.builder()
                        .authId(res)
                        .roleId(roleId)
                        .build());
            });
            this.saveBatch(lists);
        }
        nuoRoleAuthViewService.saveRoleAuthView(selectListView,roleId);

    }

    @Override
    public List<String> queryAuthIdsByRoleId(String roleId) {
        if(StrUtil.isEmpty(roleId)){
            throw new NuoException("角色id不能为空");
        }
        return nuoRoleAuthViewService.queryAuthIdsByRoleId(roleId);
    }
}
